﻿using System;
using System.Collections.Generic;
using System.Text;
using uMES.LeanManufacturing.DBUtility;
using System.Data;
using System.Xml;
using System.Web;

namespace uMES.LeanManufacturing.ReportBusiness
{
    /// <summary>
    /// 用户登录身份验证业务
    /// </summary>
    public class uMESLoginBusiness
    {
        #region 修改密码
        public Boolean UpdatePassord(string strUserName, string strPWD)
        {
            string strSQL = string.Format("UPDATE employee e SET e.password = '{0}' WHERE e.employeename = '{1}'", strPWD, strUserName);

            OracleHelper.ExecuteSql(strSQL);

            return true;
        }
        #endregion

        #region 分流OA单点登录账号
        public DataTable GetOAUserInfo(string strUserName)
        {
            StringBuilder strQuery = new StringBuilder();
            strQuery.AppendLine("SELECT e.cardnumber,e.isshopflooruser,e.iscardlogin");
            strQuery.AppendLine("FROM employee e");
            strQuery.AppendFormat("WHERE LOWER(e.employeename) = LOWER('{0}')", strUserName);

            DataTable DT = OracleHelper.GetDataTable(strQuery.ToString());
            return DT;
        }
        #endregion

        #region 刷卡登录
        /// <summary>
        /// 刷卡登录
        /// </summary>
        /// <param name="strCard"></param>
        /// <param name="strInfo"></param>
        /// <returns></returns>
        public bool CheckCardNumber(string strCard, out string strInfo)
        {
            StringBuilder strQuery = new StringBuilder();
            strQuery.AppendLine("SELECT e.cardnumber,e.isshopflooruser,e.iscardlogin");
            strQuery.AppendLine("FROM employee e");
            strQuery.AppendFormat("WHERE LOWER(e.cardnumber) = LOWER('{0}')", strCard);

            DataTable DT = OracleHelper.GetDataTable(strQuery.ToString());
            if (DT.Rows.Count == 0)
            {
                strInfo = "无效的卡号";
                return false;
            }

            int isShopfloorUser = Convert.ToInt32(DT.Rows[0]["IsShopfloorUser"].ToString());
            if (isShopfloorUser == 0)
            {
                strInfo = "该用户不是现场操作人员";
                return false;
            }

            int isCardLogin = Convert.ToInt32(DT.Rows[0]["IsCardLogin"].ToString());
            if (isCardLogin == 0)
            {
                strInfo = "该用户不允许刷卡登录";
                return false;
            }

            strInfo = "验证通过";
            return true;
        }
        #endregion

        #region 身份验证
        /// <summary>
        /// 身份验证
        /// </summary>
        /// <param name="user">用户名,不区分大小写</param>
        /// <returns></returns>
        public bool Vertification(string user, string password)
        {
            string sql =
            "select e.password from employee e\n" +
            "  where lower(e.employeename) = '"+user.ToLower()+"'";
            DataTable dt = OracleHelper.GetDataTable(sql);
            if (dt.Rows.Count == 0)
            {
                return false;
            }
            //口令密文[MD5]
            string passmd5 = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(password, "MD5");
            string passdb = dt.Rows[0][0].ToString();
            //保留明文比较方式（存在某些用户的口令在数据库中以明文方式存储）
            if (passdb == passmd5 || passdb == password)
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        /// <summary>
        /// 单点登录验证
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        public bool Vertification(string user)
        {
            string sql =
            "select e.password from employee e\n" +
            "  where lower(e.employeename) = '" + user.ToLower() + "'";
            DataTable dt = OracleHelper.GetDataTable(sql);
            if (dt.Rows.Count == 0)
            {
                return false;
            }

            return true;
        }
        #endregion

        #region 登录人信息
        /// <summary>
        /// 登录人信息
        /// </summary>
        /// <param name="user">用户名</param>
        /// <returns></returns>
        public Dictionary<string, string> GetUserInfo(string user)
        {
            string sql =
            "select e.fullname, f.factoryname, f.description, f.factoryid, e.employeeid, e.teamid, e.employeename,e.password,e.InspectorNo \n" +
            "  from sessionvalues sv\n" +
            "  left join employee e on sv.employeeid = e.employeeid\n" +
            "  left join factory f on sv.factoryid = f.factoryid\n" +
            " where lower(e.employeename) = '"+user.ToLower()+"'" +
            "   or lower(e.cardnumber) = '" + user.ToLower() + "'";
            DataTable dt = OracleHelper.GetDataTable(sql);
            Dictionary<string, string> result = new Dictionary<string, string>();
            if (dt.Rows.Count > 0)
            {
                result.Add("FullName", dt.Rows[0][0].ToString());
                result.Add("FactoryName", dt.Rows[0][1].ToString());
                result.Add("FactoryDesc", dt.Rows[0][2].ToString());
                result.Add("FactoryID", dt.Rows[0][3].ToString());
                result.Add("EmployeeID", dt.Rows[0][4].ToString());
                result.Add("TeamID", dt.Rows[0][5].ToString());
                result.Add("EmployeeName", dt.Rows[0]["EmployeeName"].ToString());
                result.Add("Password", dt.Rows[0]["Password"].ToString());
                result.Add("InspectorNo", dt.Rows[0]["InspectorNo"].ToString());
                result.Add("UserLoginInfoID", Guid.NewGuid().ToString());//add:Wangjh
                //result.Add("InspectorNo", "");
                //获取调用camstarApi的用户 add:Wangjh 20201023
                result.Add("ApiEmployeeName", dt.Rows[0]["EmployeeName"].ToString());
                result.Add("ApiPassword", dt.Rows[0]["password"].ToString());
                XmlDocument myxml = new XmlDocument();
                myxml.Load(HttpRuntime.AppDomainAppPath+ "UserAssociate.xml");
                string apiName = "", apiPassword = "";
                foreach (XmlNode u in myxml.SelectNodes("Root/FactoryApiUsers/User")) {
                    if (u.Attributes["FactoryName"].Value == result["FactoryName"].ToString()) {
                        apiName = u.Attributes["UserName"].Value;
                        apiPassword = u.Attributes["Password"].Value;
                        break;
                    }
                }
                if (!string.IsNullOrWhiteSpace(apiName))
                {
                    result["ApiEmployeeName"] = apiName;
                    result["ApiPassword"] = apiPassword;
                }
            }
            return result;
        }
        #endregion

        #region 记录用户登录信息
        public void InsertUserLogInfo(Dictionary<string,string> para) {
            string sql = @"insert into UserLoginInfo (UserLoginInfoid,Employeename,Logindate,Loginip,Logintype,Note,isonline) values ('{0}','{1}',sysdate,'{2}',{3},'{4}',1)";

            OracleHelper.ExecuteSql(string.Format(sql,para["UserLoginInfoID"],para["EmployeeName"], para["LoginIp"], para["LoginType"], para["Note"]));
        }
        #endregion
    }
}
